package com.thermofisher.dsc.amanda.common.crud;

import com.thermofisher.dsc.amanda.model.BaseModel;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Date;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;


/**
 * @author yunpeng.song
 */
public class Util {

    public static Mapper dozer = new DozerBeanMapper();

    public static <X, Y> Y convert(X x, Y y) {
        if (x == null) {
            return null;
        }
        dozer.map(x, y);
        return y;
    }

    public static <T> T convert(Object s, Class<T> klasst) {
        return dozer.map(s, klasst);
    }


    public static <X> X createInstance(Class<?> cls) {
        X obj = null;
        try {
            obj = (X) cls.newInstance();
        } catch (Exception e) {
            obj = null;
        }
        return obj;
    }

    public static Class<?> getActualArgumentType(Class<?> clazz, int index) {
        Class<?> entitiClass = null;
        Type genericSuperclass = clazz.getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType) {
            Type[] actualTypeArguments = ((ParameterizedType) genericSuperclass)
                .getActualTypeArguments();
            if (actualTypeArguments != null && actualTypeArguments.length > index) {
                entitiClass = (Class<?>) actualTypeArguments[index];
            }
        }
        return entitiClass;
    }


    public static void populateAuditInfo(BaseModel dto, boolean isCreate) {
        if (dto == null) {
            return;
        }
        Date date = new Date();
        dto.setUpdateTime(date);
        if (isCreate) {
            dto.setCreateTime(date);
        }
    }


}
